<template>
  <div>
    <!-- 主内容区域 -->
    <div class="all" v-show="!dialogVisible">
      <!-- 搜索框区域 -->
      <div class="search_box">
        <div>
          <div class="search_title">商品</div>
          <el-input v-model="input" class="seek" placeholder="请输入标题" />
        </div>
        <div class="search_right">
          <div class="search_title">创建时间</div>
          <el-date-picker v-model="value1" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" size="default" @change="debouncedSearch" />
        </div>
      </div>
      <div class="line"></div>

      <!-- 操作按钮区域 -->
      <div class="button_box">
        <el-button type="primary" class="butten" @click="adds()">新增</el-button>
        <el-button type="danger" class="butten" @click="deleteSelectedRows">
          批量删除
        </el-button>
      </div>

      <!-- 表格展示区域 -->
      <div class="table_box">
        <el-table :data="paginatedData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="120" align="center">
            <template #default="scope">{{ scope.row.id }}</template>
          </el-table-column>
          <el-table-column property="title" label="名称" width="150" align="center" />
          <el-table-column property="classname" label="分类名称" align="center" />
          <el-table-column property="content" label="简介" align="center" show-overflow-tooltip />
          <el-table-column property="price" label="价格" align="center" show-overflow-tooltip />
          <el-table-column property="address" label="图片" align="center">
            <template #default="scope">
              <el-image style="width: 60px; height: 60px" :src="url + scope.row.img" :zoom-rate="1.2" :max-scale="7"
                :min-scale="0.2" :preview-src-list="[url + scope.row.img]" :initial-index="4" fit="cover" />
            </template>
          </el-table-column>
          <el-table-column label="商品状态" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.showBoolean" @change="changeSwitch(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center">
            <template #default="scope">{{ scope.row.createtime }}</template>
          </el-table-column>
          <el-table-column property="address" label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" @click="edit(scope.row)" text>编辑</el-button>
              <el-button type="danger" @click="deletes(scope.row.id)" text>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 对话框区域 -->
    <div class="windows" v-show="dialogVisible">
      <div class="windows_box">
        <div class="windows_title">{{ titles }}</div>
        <div class="line"></div>

        <el-form ref="ruleFormRef" label-width="110px" :model="ruleForm" :rules="rules">
          <div class="windows_content">
            <div class="content_left">
              <el-form-item label="商品名称" label-position="left" prop="title">
                <el-input v-model="ruleForm.title" style="width: 280px" placeholder="请输入商品名称" />
              </el-form-item>
              <el-form-item label="商品分类" label-position="left" prop="type">
                <el-select v-model="ruleForm.type" style="width: 280px" placeholder="请选择分类" @change="validateSelect">
                  <el-option v-for="item in arr" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="商品轮播" label-position="left" prop="fileLists">
                <el-upload v-model:file-list="ruleForm.fileLists" :before-upload="checkImageLimit"
                  list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemoves" :limit="3">
                  <el-icon v-if="ruleForm.fileLists.length < 3">
                    <Plus />
                  </el-icon>
                  <div v-else class="el-upload__tip" style="font-size: 12px">最多上传3张</div>
                </el-upload>
                <div class="el-upload__tip">请上传1-3张轮播图片</div>
              </el-form-item>
            </div>
            <div class="content_right">
              <el-form-item label="商品价格" label-position="left" prop="price">
                <el-input-number v-model="ruleForm.price" :min="1" @change="handleChange" />
              </el-form-item>
              <el-form-item label="商品好评" label-position="left" prop="good_reviews">
                <el-input-number v-model="ruleForm.good_reviews" :min="1" @change="handleChange" />
              </el-form-item>
              <el-form-item label="商品库存" label-position="left" prop="stock">
                <el-input-number v-model="ruleForm.stock" :min="1" @change="handleChange" />
              </el-form-item>
              <el-form-item label="商品封面" label-position="left" prop="img">
                <el-upload class="avatar-uploader" :file-list="fileList" v-model="ruleForm.img" list-type="picture-card"
                  :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                  :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                  <el-icon class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
            </div>
          </div>

          <div class="UEditors">
            <el-form-item label="商品简介" label-position="left" prop="content" style="margin-left: 10%; margin-top: 50px">
              <UEditor v-if="dialogVisible" v-model="ruleForm.content" />
            </el-form-item>
          </div>

          <div class="windows_content_box">
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
              <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="business">
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, onMounted, ref, watch, computed } from "vue";
import { goodsList, goodsAdd, goodsDel, goodsStatus } from "/@/api/score/score_goods/index";
import { goodsTypeList } from "/@/api/score/score_goods_type/index";
import UEditor from "../../../components/UEeditor/index.vue";
import "/src/css/business.css";
import axios from "axios";
import { url } from "/@/api/url";
import { Plus } from "@element-plus/icons-vue";
import type { UploadUserFile } from "element-plus";

// 基础变量定义
const arr = ref([]);
const delid = ref([]);
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const value1 = ref<[Date, Date] | null>(null);
const input = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const data = ref([]);
const dialogVisible = ref(false);
const edit_add = ref(false);
const originalData = ref([]);
const selectedRows = ref([]);
const titles = ref("");
const swiperList = ref([]); // 新增：用于搜索过滤的临时数组
const filteredData = ref([]); // 新增：过滤后的数据

// 表单相关
const ruleFormRef = ref();
const ruleForm = reactive({
  title: "",
  status: "",
  content: "",
  fileLists: [] as UploadUserFile[], // 轮播图文件列表
  imgs: "", // 轮播图URL拼接字符串
  good_reviews: 0,
  price: 0,
  stock: 0,
  type: "",
  jobc_time: "",
  id: "",
  img: "" // 封面图
});

// 修复：优化轮播图验证规则
const rules = reactive({
  title: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  content: [{ required: true, message: "请输入商品内容", trigger: "blur" }],
  good_reviews: [{ required: true, message: "请输入商品好评", trigger: "change" }],
  price: [{ required: true, message: "请输入商品价格", trigger: "change", type: "number" }],
  stock: [{ required: true, message: "请输入商品库存", trigger: "change", type: "number" }],
  img: [{ required: true, message: "请上传商品封面", trigger: ["change", "blur"] }],
  type: [
    { required: true, message: "请选择商品分类", trigger: "change" },
    { type: "number", message: "分类选择无效", trigger: "change" }
  ],
  // 轮播图验证：监听fileLists变化，检查长度
  fileLists: [
    {
      required: true,
      message: "请至少上传1张轮播图",
      trigger: "change" // 关键：文件列表变化时触发验证
    },
    {
      validator: (rule, value, callback) => {
        if (value.length > 3) {
          callback(new Error("最多上传3张轮播图"));
        } else {
          callback();
        }
      },
      trigger: "change" // 关键：文件列表变化时触发验证
    }
  ]
});

// 计算属性：分页数据
const paginatedData = computed(() => {
  let filteredData = originalData.value;

  if (input.value) {
    filteredData = filteredData.filter(item =>
      item.title?.toLowerCase().includes(input.value.toLowerCase())
    );
  }

  if (value1.value && value1.value.length === 2) {
    const startTime = new Date(value1.value[0]).getTime();
    const endTime = new Date(value1.value[1]).getTime();
    filteredData = filteredData.filter(item => {
      const itemTime = new Date(item.createtime).getTime();
      return itemTime >= startTime && itemTime <= endTime;
    });
  }

  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  total.value = filteredData.length;
  return filteredData.slice(start, end);
});

// 重置表单
function resetFormFields() {
  ruleForm.id = "";
  ruleForm.img = "";
  ruleForm.imgs = "";
  ruleForm.type = "";
  ruleForm.title = "";
  ruleForm.status = "";
  ruleForm.content = "";
  ruleForm.good_reviews = 0;
  ruleForm.price = 0;
  ruleForm.stock = 0;
  ruleForm.jobc_time = "";
  ruleForm.fileLists = []; // 清空轮播图列表
  fileList.value = [];
  dialogImageUrl.value = "";
}

// 新增商品
function adds() {
  titles.value = "新增";
  edit_add.value = true;
  resetFormFields();
  dialogVisible.value = true;
}

// 编辑商品（修复：轮播图验证触发）
function edit(row: any) {
  titles.value = "编辑";
  edit_add.value = false;
  row.price = parseFloat(row.price); // 确保价格为数字

  // 复制数据到表单
  Object.assign(ruleForm, row);

  // 处理轮播图
  if (row.imgs) {
    ruleForm.fileLists = row.imgs.split(",").map((imgUrl: string) => ({
      name: "商品图片",
      url: `${url}${imgUrl}`
    }));
  } else {
    ruleForm.fileLists = [];
  }

  // 处理封面图
  if (row.img) {
    fileList.value = [{ name: "商品封面", url: `${url}${row.img}` }];
  }

  dialogVisible.value = true;

  // 修复：编辑时手动触发轮播图验证
  nextTick(() => {
    ruleFormRef.value?.validateField("fileLists");
  });
}

// 防抖搜索
function debouncedSearch() {
  // 延迟执行搜索，避免频繁触发
  setTimeout(() => {
    // 触发计算属性更新
    input.value = input.value;
  }, 500);
}

// 状态切换
const changeSwitch = (val: any) => {
  val.status = val.status === 1 ? 0 : 1;
  goodsStatus({ ids: val.id, status: val.status })
    .then(() => {
      ElMessage.success("操作成功！");
      fetchAndRefreshData();
    })
    .catch(() => {
      ElMessage.error("操作失败，请稍后再试！");
    });
};

// 轮播图上传前检查
function checkImageLimit(rawFile: File): boolean {
  if (ruleForm.fileLists.length >= 3) {
    ElMessage.error('最多只能上传3张图片');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2MB!");
    return false;
  }
  const form = new FormData();
  form.append("file", rawFile);
  axios.post(`${url}/pc/common/upload`, form).then(handleImageUploadSuccesss);
  return false;
}

// 轮播图上传成功（修复：同步fileLists和imgs）
function handleImageUploadSuccesss(response: any) {
  const imgUrl = response.data.data.url;
  // 处理首次上传（避免开头出现逗号）
  ruleForm.imgs = ruleForm.imgs ? `${ruleForm.imgs},${imgUrl}` : imgUrl;
  ruleForm.fileLists.push({
    name: "商品图片",
    url: `${url}${imgUrl}`
  });
  // 修复：上传成功后触发验证
  ruleFormRef.value?.validateField("fileLists");
}

// 封面图上传成功
function handleAvatarSuccess(response: any) {
  ruleForm.img = response.data.data.url;
  fileList.value = [{ name: "商品封面", url: `${url}${response.data.data.url}` }];
}

// 移除封面图
function handleRemove() {
  fileList.value = [];
  ruleForm.img = "";
  ruleFormRef.value?.validateField("img"); // 触发封面图验证
}

// 移除轮播图（修复：同步imgs并触发验证）
function handleRemoves(uploadFile: UploadUserFile) {
  const urlToRemove = uploadFile.url.split(url)[1]; // 提取相对路径
  // 更新imgs字符串
  ruleForm.imgs = ruleForm.imgs
    .split(",")
    .filter(url => url !== urlToRemove)
    .join(",");
  // 更新fileLists
  ruleForm.fileLists = ruleForm.fileLists.filter(file => file.url !== uploadFile.url);
  // 修复：删除后触发验证
  ruleFormRef.value?.validateField("fileLists");
}

// 监听搜索输入
watch(input, () => {
  filteredData.value = swiperList.value.filter(item =>
    item.title?.includes(input.value)
  );
});

// 分页相关
function handleSizeChange(newSize: number) {
  pageSize.value = newSize;
  currentPage.value = 1;
}

function handleCurrentChange(newCurrentPage: number) {
  currentPage.value = newCurrentPage;
}

// 提交表单
function submitForm(formEl: any) {
  if (!formEl) return;

  formEl.validate((valid: boolean) => {
    if (valid) {
      ruleForm.status = ruleForm.status === "上架" ? 1 : 2;
      // 区分新增/编辑接口
      const api = edit_add.value ? goodsAdd : goodsAdd; // 假设编辑也是用同一个接口，实际需替换为编辑接口
      api(ruleForm)
        .then((res) => {
          if (res.code === 1) {
            ElMessage.success("提交成功!");
            dialogVisible.value = false;
            fetchAndRefreshData();
          } else {
            ElMessage.error("提交失败!");
          }
        })
        .catch((error) => {
          ElMessage.error("提交失败：" + error.message);
        });
    } else {
      ElMessage.warning("请填写完整信息！");
      return false;
    }
  });
}

// 刷新数据
function fetchAndRefreshData() {
  goodsList().then((res) => {
    originalData.value = res.data.map((item: any) => ({
      ...item,
      showBoolean: item.status === 1
    }));
    data.value = [...originalData.value];
  });

  goodsTypeList({ page: 1, pageSize: 10 }).then((res) => {
    arr.value = res.data.map((item: any) => ({
      label: item.title,
      value: item.id
    }));
  });
}

// 重置表单
function resetForm(formEl: any) {
  dialogVisible.value = false;
  if (formEl) {
    formEl.resetFields();
  }
  resetFormFields();
}

// 验证分类
function validateSelect() {
  ruleFormRef.value?.validateField('type');
}

// 删除单个商品
const deletes = (id: any) => {
  ElMessageBox.confirm("确定要删除此条数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      goodsDel({ ids: JSON.stringify(id) })
        .then((res) => {
          if (res.code === 1) {
            ElMessage.success("删除成功");
            fetchAndRefreshData();
          }
        })
        .catch((error) => {
          ElMessage.error("删除失败：" + error.message);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 批量删除
const deleteSelectedRows = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的记录");
    return;
  }

  ElMessageBox.confirm("确定要删除选中的记录吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      goodsDel({ ids: selectedRows.value.join(",") })
        .then((res) => {
          if (res.code === 1) {
            ElMessage.success("删除成功");
            fetchAndRefreshData();
          }
        })
        .catch((error) => {
          ElMessage.error("删除失败：" + error.message);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 处理选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows.map(row => row.id);
};

// 数值变化处理
function handleChange(value: number) {
  // 可添加数值格式化逻辑
}

// 图片预览
function handlePictureCardPreview(file: UploadUserFile) {
  dialogImageUrl.value = file.url;
}

// 封面图上传前检查
function beforeAvatarUpload(rawFile: File): boolean {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2MB!");
    return false;
  }
  return true;
}

// 初始化
onMounted(() => {
  fetchAndRefreshData();
});
</script>

<style lang="scss">
.el-table .el-table__cell.is-center {
  position: unset !important;
}

// 补充上传组件样式
.el-upload__tip {
  color: #606266;
  margin-top: 5px;
  font-size: 12px;
}
</style>